package com.dingreading.cloud.soms.controller;

import com.alibaba.excel.EasyExcel;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.LoginDataDto;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.common.util.excel.ExcelHandler;
import com.dingreading.cloud.soms.dto.CmservicesDto;
import com.dingreading.cloud.soms.entity.Cmservices;
import com.dingreading.cloud.soms.service.CmservicesService;
import com.dingreading.cloud.soms.util.CmorderUtil;
import com.dingreading.cloud.soms.util.LoginInfoUtil;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping(value = "/front/cmService")
@Api(tags = "门店-会员服务项目管理")
public class FrontCmServiceController {

    @Resource
    private CmservicesService cmservicesService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "订单号/会员姓名/服务产品名称") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "开卡状态 未开通:-1，暂停服务:0，服务中:1") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "开始日期") @RequestParam(value = "beginDate", required = false) String beginDate,
            @ApiParam(value = "结束日期") @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(value = "查询类型 1.即将过期 2.已过期 3.活动次数不足 4.剩余活动次数") @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(value = "赠送状态 1.赠送 0.非赠送") @RequestParam(value = "gift", required = false) Integer gift
    ) {
        Page<CmservicesDto> page = cmservicesService.storePage(pageUtil, storeUid, keyword, beginDate, endDate, status, type, gift);

        List<CmservicesDto> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            // 已开卡且可排活动的服务uid集合，获取消耗数量
            Map<String, Long> consumeMap = CmorderUtil.getConsumeLessonMapByDto(list);

            // 服务获取已活动次数，状态名称修改
            CmorderUtil.setUseLessonCntAndStatusName(list, consumeMap);
        }

        PageBeanDto data = new PageBeanDto();
        data.setTotal(page.getTotalRow());
        data.setList(list);
        return R.ok(data);
    }

    @ApiOperation(value = "导出服务")
    @PostMapping(value = "/exportList", produces = "application/vnd.ms-excel;charset=UTF-8")
    public void exportList(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "订单号/会员姓名/服务产品名称") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "开卡状态 未开通:-1，暂停服务:0，服务中:1") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "开始日期") @RequestParam(value = "beginDate", required = false) String beginDate,
            @ApiParam(value = "结束日期") @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(value = "查询类型 1.即将过期 2.已过期 3.活动次数不足 4.剩余活动次数") @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(value = "赠送状态 1.赠送 0.非赠送") @RequestParam(value = "gift", required = false) Integer gift
    ) throws Exception {
        // 获取员工信息
        R<Object> result = LoginInfoUtil.getLoginDto(request);
        if (result.getSt() != 0) throw new DescribeException(500, result.getMsg());
        LoginDataDto loginDto = (LoginDataDto) result.getData();

        if (!AccountUtil.isStoreManager(loginDto.getStoreRoles()))
            throw new DescribeException("非店长账号，不能操作");

        if (type == null)
            //  获取本月的第一天和最后一天
            if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
                Date monthMinDate = DateUtil.getMonthMinDate();
                Date monthMaxDate = DateUtil.getMonthMaxDate();
                beginDate = DateUtil.getDefaultTime2DateStr(monthMinDate);
                endDate = DateUtil.getDefaultTime2DateStr(monthMaxDate);
            }

        List<CmservicesDto> list = cmservicesService.exportList(storeUid, keyword, beginDate, endDate, status, type, gift);
        if (CollectionUtils.isEmpty(list))
            throw new DescribeException(beginDate + "至" + endDate + "，未查询到信息");

        // 已开卡且可排活动的服务uid集合，获取消耗数量
        Map<String, Long> consumeMap = CmorderUtil.getConsumeLessonMapByDto(list);

        // 服务获取已活动次数，状态名称修改
        CmorderUtil.setUseLessonCntAndStatusName(list, consumeMap);

        // 表格头部列的数据
        List<List<String>> headList = new ArrayList<>();
        headList.add(Collections.singletonList("订单号"));
        headList.add(Collections.singletonList("会员名称"));
        headList.add(Collections.singletonList("收款日期"));
        headList.add(Collections.singletonList("收入类型"));
        headList.add(Collections.singletonList("是否赠送"));
        headList.add(Collections.singletonList("服务名称"));
        headList.add(Collections.singletonList("开始/结束日期"));
        headList.add(Collections.singletonList("活动次数"));
        headList.add(Collections.singletonList("剩余活动次数"));
        headList.add(Collections.singletonList("已活动次数"));
        headList.add(Collections.singletonList("导读员"));
        headList.add(Collections.singletonList("开卡状态"));
        headList.add(Collections.singletonList("结课状态"));
        // 表格内的数据
        List<List<Object>> dataList = new ArrayList<>();

        for (CmservicesDto dto : list) {
            List<Object> data = new ArrayList<>();
            data.add(dto.getOrderCode());
            data.add(dto.getMemberName());
            if (dto.getOrderDate() != null)
                data.add(DateUtil.getDefaultTime2DateStr(dto.getOrderDate()));
            else
                data.add("");
            data.add(EnumType.OrderType.getName(dto.getOrderType()));
            data.add(dto.getIsGift().equals(1) ? "赠送" : "非赠送");
            data.add(CmorderUtil.getProductName(dto));
            if (dto.getBeginDate() != null && dto.getEndDate() != null)
                data.add(DateUtil.getDefaultTime2DateStr(dto.getBeginDate()) + "至" + DateUtil.getDefaultTime2DateStr(dto.getEndDate()));
            else
                data.add("");
            data.add(dto.getTotalLessons());
            data.add(dto.getLeftLessons());
            data.add(dto.getUseLessonCnt());
            data.add(dto.getStaffFullName());
            data.add(dto.getStatusName());
            String endStatus = dto.getEnding() != null && dto.getEnding().equals(1) ? "已结课" : "未结课";
            data.add(endStatus);

            dataList.add(data);
        }

        String fileName = "";
        if (type == null)
            fileName = "会员服务" + beginDate + "至" + endDate;
        else
            fileName = "会员服务";
        EasyExcel.write(ExcelHandler.getOutputStream(fileName, response))
                // 设置单元格样式
                .registerWriteHandler(ExcelHandler.getCellStyleStrategy())
                .head(headList)
                .sheet("会员服务")
                .doWrite(dataList);
    }

    @ApiOperation(value = "服务结课")
    @PostMapping(value = "/finishService", produces = "application/json; charset=UTF-8")
    public R<Object> finishService(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "订单号") @RequestParam(value = "orderCode") String orderCode,
            @ApiParam(value = "服务uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "结课原因") @RequestParam(value = "endingRemark") String endingRemark
    ) {
        Cmservices service = cmservicesService.getByUid(storeUid, orderCode, uid);
        if (service == null)
            return R.fail("未查询到服务");
        if (service.getChangeStatus() != null && !service.getChangeStatus().equals(0))
            return R.fail("服务已申请变更，不能操作");
        if (!service.getEnding().equals(0))
            return R.fail("已结课，不能操作");
        if (StringUtils.isBlank(endingRemark))
            return R.fail("请填写结课原因");

        boolean b = cmservicesService.setFinish(storeUid, orderCode, uid, endingRemark, staffUid, staffName);
        if (!b)
            return R.fail("操作失败");

        return R.ok();
    }

    @ApiOperation(value = "恢复已结课服务")
    @PostMapping(value = "/recoverService", produces = "application/json; charset=UTF-8")
    public R<Object> recoverService(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "订单号") @RequestParam(value = "orderCode") String orderCode,
            @ApiParam(value = "服务uid") @RequestParam(value = "uid") String uid
    ) {
        Cmservices service = cmservicesService.getByUid(storeUid, orderCode, uid);
        if (service == null)
            return R.fail("未查询到服务");
        if (!service.getEnding().equals(1))
            return R.fail("未结课，不能操作");
        if (!service.getEndingType().equals(3))
            return R.fail("不是手动结课，不能操作");

        boolean b = cmservicesService.setRecover(storeUid, orderCode, uid, staffUid, staffName);
        if (!b)
            return R.fail("操作失败");

        return R.ok();
    }

}
